package com.namo.cchapi.handler;

import com.namo.cchcommon.api.CommonResult;
import com.namo.cchcommon.api.ResultCode;
import com.namo.cchcommon.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.ServletException;

/**
 * 错误处理
 * @author WangXin
 * @date 2021/4/16 17:08
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 请求方法不支持处理
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Object handleHttpException(ServletException e) {
        log.error("(请求方法不支持)ServletException: ", e);
        return CommonResult.failed(ResultCode.FAILED, e.getMessage());
    }

    /**
     * 全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e) {
        log.error("(全局错误)Default Exception: ", e);
        return CommonResult.failed(ResultCode.FAILED, e.getMessage());
    }

    /**
     * 参数校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Object handleMethodArgumentNotValidException(
            MethodArgumentNotValidException e) {
        log.error("（参数校验错误）MethodArgumentNotValidException: ", e);
        return CommonResult.failed(ResultCode.FAILED, e.getMessage());
    }

    /**
     * 参数类型错误
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Object handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        log.error("（参数类型错误）MethodArgumentTypeMismatchException: ", e);
        return CommonResult.failed(ResultCode.FAILED, e.getMessage());
    }

    /**
     * 参数缺少
     * @param e
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public Object handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("（参数缺少错误）MissingServletRequestParameterException: ", e);
        return CommonResult.failed(ResultCode.FAILED, e.getMessage());
    }

    /**
     * api错误
     * @param e
     * @return
     */
    @ExceptionHandler(ApiException.class)
    @ResponseBody
    public Object handleApiException(ApiException e) {
        log.error("（API错误）ApiException", e);
        return CommonResult.failed(ResultCode.FAILED, e.getMessage());
    }

}
